﻿#pragma warning(disable:4005)
#include <drogon/HttpController.h>
#include "OCMain/Environment.h"
#include "OCMain/StringUtil.h"
#include "OCMain/FileUtil.h"
#include "OCServer/ServerUtil.h"
#include "OCServer/MapManager.h"

using namespace OCPP;
using namespace drogon;
using namespace drogon::orm;

inline void setGZIp(HttpResponsePtr& resp)
{
	resp->addHeader("Content-Encoding", "gzip");
}

inline ContentType getContentType(String layer, String ext)
{
	ContentType contentType = CT_NONE;
	static std::map<String, ContentType> caches;
	auto it = caches.find(layer);
	if (it != caches.end())
	{
		contentType = it->second;
	}
	else
	{
		if (ext == "png")
		{
			contentType = CT_IMAGE_PNG;
		}
		else if (ext == "jpg")
		{
			contentType = CT_IMAGE_JPG;
		}
		else if (ext == "gz")
		{
			contentType = CT_APPLICATION_OCTET_STREAM;
		}
		caches[layer] = contentType;
	}

	return contentType;
}

class v1 : public HttpController<v1>
{
public:
	METHOD_LIST_BEGIN
	METHOD_ADD(v1::home, "", Get);
	METHOD_ADD(v1::Gtiles, "{}", { Get });
	METHOD_ADD(v1::Gtiles, "{}/{}", { Get });
	METHOD_ADD(v1::Gtiles, "{}/{}/{}", { Get });
	METHOD_ADD(v1::Gtiles, "{}/{}/{}/{}", { Get });
	METHOD_ADD(v1::Gtiles, "{}/{}/{}/{}/{}", { Get });
	METHOD_ADD(v1::Gtiles, "{}/{}/{}/{}/{}/{}", { Get });
	METHOD_ADD(v1::Gtiles, "{}/{}/{}/{}/{}/{}/{}", { Get });
	METHOD_LIST_END
protected:
	void home(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback)
	{
		auto resp = HttpResponse::newHttpResponse();
		resp->setBody("v1");
		callback(resp);
	}

	void Gtiles(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback)
	{
		auto resp = HttpResponse::newHttpResponse();
		String requestPath = req->getOriginalPath();
		String p = req->getPath();
		auto parameters = req->getParameters();
		requestPath = requestPath.substr(4, requestPath.length());
		int i = 0;
		for (auto& [k, v] : parameters)
		{
			requestPath += i == 0 ? "?" : "&";
			requestPath += k + "=" + v;
			i++;
		}

		auto data = Singleton(MapManager).get3dtiles("Google3dtiles", requestPath);
		if (!data.empty())
		{
			resp = drogon::HttpResponse::newFileResponse((const unsigned char*)data.data(), data.length(), "",
				CT_APPLICATION_OCTET_STREAM);
		}
		callback(resp);
	}
};